#include <iostream>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
using namespace std;
class Server
{
    typedef function<void(int, string, uint16_t, string)> func_t;

public:
    Server(const func_t func, const uint16_t &port, const string &ip = "0.0.0.0") : _func(func), _port(port), _ip(ip) {}
    void init()
    {
        _fd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_fd == -1)
        {
            cerr << "socket :" << strerror(errno) << endl;
            exit(1);
        }
        cerr << "socket succcess" << endl;

        struct sockaddr_in addr;
        bzero(&addr, sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(_port);
        addr.sin_addr.s_addr = inet_addr(_ip.c_str());
        int n = bind(_fd, (const sockaddr *)&addr, sizeof(addr));
        if (n != 0)
        {
            cerr << "bind error : " << strerror(errno) << endl;
            exit(2);
        }
        cerr << "bind success" << endl;
    }
    void start()
    {
        char buffer[1024];
        while (1)
        {
            struct sockaddr_in addr;
            socklen_t len = sizeof(addr);
            size_t n = recvfrom(_fd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&addr, &len);
            if (n > 0)
            {
                buffer[n] = 0;
                uint16_t port = ntohs(addr.sin_port);
                string ip = inet_ntoa(addr.sin_addr);
                string messages = buffer;
                _func(_fd, ip, port, messages);
            }
        }
    }

private:
    func_t _func;
    int _fd;
    uint16_t _port;
    string _ip;
};